<template>
  <div class="h-full w-full flex flex-col justify-between">
    <div class="form p-[15px] pb-0">
      <el-form>
        <el-row :gutter="12">
          <el-col :span="2">
            <el-button type="primary" @click="handleOpen()">添加子账号</el-button>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-input v-model="form.name" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-button type="primary" @click.stop="search">搜索</el-button>
            <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="grow-[1] h-0 mx-[15px]">
      <el-table
        scrollbar-always-on
        v-loading="state.loading"
        :data="list"
        height="100%"
        border
        stripe
        fit
      >
        <template #empty>
          <ui-empty />
        </template>
        <el-table-column align="center" prop="Name" label="用户名" show-overflow-tooltip />
        <el-table-column align="center" prop="Remark" label="备注" show-overflow-tooltip>
          <template #default="{ row }: TableItem"> {{ row.Remark || "--" }}</template>
        </el-table-column>
        <el-table-column align="center" prop="IsUsed" label="状态">
          <template #default="{ row }: TableItem">
            <el-dropdown placement="bottom" @command="(e: number) => handleChangeStatus(row, e)">
              <el-button :type="typeMap[row?.IsUsed]?.type" size="small">
                {{ typeMap[row?.IsUsed]?.text || "--" }}
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :disabled="row.IsUsed == 1" :command="1">
                    正常
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="row.IsUsed == 0" :command="0">
                    关闭
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }: TableItem">
            <el-button type="primary" size="small" @click="handleEdit(row)"> 编辑 </el-button>
            <el-button type="primary" size="small" @click="handleReset(row)">
              重置二次验证
            </el-button>
            <el-button type="danger" size="small" @click="handleDel(row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-end my-[10px] mx-[15px]">
      <ui-pagination
        :total="state.total"
        v-model:pageSize="state.pageSize"
        v-model:currentPage="state.page"
        @current-change="getData"
      ></ui-pagination>
    </div>
    <sub-edit-dialog :row="curData" :type="type" ref="subEditDialogRef" @update="getData" />
  </div>
</template>
<script setup lang="ts">
import SubEditDialog from "./components/sub-edit-dialog.vue";
import { useList } from "@/hooks/useList";
import { reqUserSubAccountsDel, reqUserSubAccountsEdit, reqUserSubAccountsList } from "@/api/user";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { usePremsStore } from "@/store/modules/prems";
import { reqGoogleSecretReset } from "@/api/main";

interface TableItem {
  row: SubAccountMo;
}
const form = reactive<{
  name: string;
}>({
  name: ""
});
const router = useRouter();
const route = useRoute();
const premsStore = usePremsStore();
const subEditDialogRef = ref();
const curData = ref<SubAccountMo | null>(null);
const type = ref<"add" | "edit">("add");

const typeMap = reactive<Record<string, TextType>>({
  0: { text: "关闭", type: "danger" },
  1: { text: "正常", type: "success" }
});

const getParams = () => {
  const params = {
    ...(form.name ? { Name: form.name } : {})
  };
  return params;
};
const { state, list, search, getData } = useList<SubAccountMo, { Name?: string }>(
  reqUserSubAccountsList,
  getParams
);

// 重置
const handleRefresh = () => {
  form.name = "";
  search();
};

const handleOpen = () => {
  curData.value = null;
  type.value = "add";
  nextTick(() => {
    subEditDialogRef.value?.open();
  });
};

const handleEdit = (row: SubAccountMo) => {
  curData.value = row;
  type.value = "edit";
  nextTick(() => {
    subEditDialogRef.value?.open();
  });
};

// 删除
const handleDel = (row: SubAccountMo) => {
  ElMessageBox.confirm(`是否进行【删除】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqUserSubAccountsDel({
            Id: row.Id
          });
          instance.confirmButtonLoading = false;
          message.success("子账号删除成功");
          getData();
          done(); // 操作成功后关闭对话框
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

// 重置谷歌验证器
const handleReset = (row: SubAccountMo) => {
  ElMessageBox.confirm(`是否【重置】该子账号二次验证？`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqGoogleSecretReset({
            Id: row.Id
          });
          instance.confirmButtonLoading = false;
          message.success("重置成功");
          done(); // 操作成功后关闭对话框
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

// 修改状态
const handleChangeStatus = async (row: SubAccountMo, key: number) => {
  try {
    state.loading = true;
    await reqUserSubAccountsEdit({
      Id: row?.Id,
      Name: row.Name,
      Remark: row.Remark,
      IsUsed: key,
      Perms: row.Perms
    });
    message.success("修改状态成功");
    state.loading = false;
    row.IsUsed = key;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};
watch(
  () => route.path,
  val => {
    if (!premsStore.isRoomAdmin && val == "/admin/user/sub") {
      router.replace("/admin/user/member");
    }
  }
);

onMounted(() => {
  if (!premsStore.isRoomAdmin) {
    router.replace("/admin/user/member");
  } else {
    getData();
  }
});
</script>
<style lang="scss" scoped>
:deep(.el-table__row) {
  cursor: pointer;
}
</style>
